package com.amran.dynamic.multitenant.acp;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.amran.dynamic.multitenant.configuration.ResponseMessageConfiguration;
import com.amran.dynamic.multitenant.exception.BadRequestException;
import com.amran.dynamic.multitenant.exception.HttpException;
import com.amran.dynamic.multitenant.exception.NotFoundException;
import com.amran.dynamic.multitenant.support.UnifyResponse;
import com.amran.dynamic.multitenant.util.HttpRequestUtil;

@ResponseBody
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
	@Autowired
	private ResponseMessageConfiguration responseMessage;

	@ExceptionHandler({ BadRequestException.class, NotFoundException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public UnifyResponse<Object> HandlerException(HttpServletRequest request, HttpException exception) {
		String message = responseMessage.message(exception.getCode());
		String req = HttpRequestUtil.getSimpleMessage(request);
		return new UnifyResponse<Object>(exception.getCode(), message, req);
	}

	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public UnifyResponse<Object> handlerConstraintViolationException(HttpServletRequest request,
			ConstraintViolationException exception) {
		String message = getConstraintErrorsMessage(exception);
		String req = HttpRequestUtil.getSimpleMessage(request);
		return new UnifyResponse<Object>(HttpStatus.BAD_REQUEST.value(), message, req);
	}

	private String getConstraintErrorsMessage(ConstraintViolationException exception) {
		StringBuilder buffer = new StringBuilder();
		for (ConstraintViolation<?> error : exception.getConstraintViolations()) {
			buffer.append(error.getMessage()).append(";");
		}
		return buffer.toString();
	}
}
